package com.java1234.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.java1234.entity.*;
import com.java1234.service.*;
import com.java1234.util.ScoreCalculator;
import com.java1234.util.StringUtil;
import com.java1234.util.UserAnswersCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 考试Controller
 */
@RestController
@RequestMapping("/bsns/subject/examinations")
public class ExaminationController {
    @Autowired private ExaminationService examinationService;

    @Autowired private ExamQuestionService examQuestionService;

    @Autowired private QuestionService questionService;

    @Autowired
    private ScoreCalculator scoreCalculator;

    @Autowired
    private ExamHistoryService examHistoryService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private AnswerService answerService;

    @Autowired
    private ExamDetailService examDetailService;

    /**
     * 查询所有考试信息
     * @return
     */
    @GetMapping("/listAll")
    public R listAll(){
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("examinations",examinationService.list());
        return R.ok(resultMap);
    }

    /**
     * 分页查询考试信息
     * @param pageBean
     * @return
     */
    @PostMapping("/list")
    public R list(@RequestBody PageBean pageBean){
        String query = pageBean.getQuery().trim();
        QueryWrapper<Examination> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(query)) {
            queryWrapper.like("name", query);
        }
        if (pageBean.getStatus() != null) {
            queryWrapper.eq("status", pageBean.getStatus());
        }
        if(pageBean.getDifficultylevel()!=null){
            queryWrapper.eq("difficultylevel",pageBean.getDifficultylevel());
        }
        Page<Examination> pageRes = examinationService.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), queryWrapper);
        List<Examination> examinations = pageRes.getRecords();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("examinations", examinations);
        resultMap.put("total", pageRes.getTotal());
        return R.ok(resultMap);
    }

    /**
     * 根据ID查询考试信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getExaminationById(@PathVariable(value="id") Long id) {
        Examination examination = examinationService.getById(id);
        if (examination == null) {
            return R.error("没找到");
        }
        return R.ok().put("examinations", examination);
    }

    /**
     * 添加考试信息
     * @param examination
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody Examination examination){
        boolean isSaved=examinationService.save(examination);
        if(isSaved){
            return R.ok("添加成功");
        }else{
            return R.error("添加失败");
        }
    }

    /**
     * 删除考试信息
     * @param ids
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        // 删除 exam_question 表中的相关记录
        examQuestionService.removeByExaminationIds(Arrays.asList(ids));
        // 删除 examination 表中的记录
        examinationService.removeByIds(Arrays.asList(ids));
        return R.ok("删除成功");
    }

    /**
     * 更新考试信息
     * @param examination
     * @return
     */
    @PostMapping("/update")
    public R update(@RequestBody Examination examination){
        boolean isUpdated=examinationService.updateById(examination);
        if(isUpdated){
            return R.ok("修改成功");
        }else{
            return R.error("修改失败");
        }
    }

    /**
     * 根据考试ID查询考试试题
     * @return
     */
    @GetMapping("/maxId")
    public R getMaxExaminationId(){
        Integer maxId=examinationService.getMaxExaminationId();
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("maxId",maxId);
        return R.ok().put("maxId",maxId);
    }

    /**
     * 根据考试ID查询考试试题
     * @param data
     * @return
     */
    @PostMapping("/submitExam")
    public R submitExam(@RequestBody Map<String, Object> data) {
        // 获取 examId 和用户的 answers
        Long examId = Long.valueOf(data.get("examId").toString());
        String username = getCurrentUsername();
        SysUser currentUser = sysUserService.getByUsername(username);
        if (currentUser == null) {
            return R.error("用户不存在");
        }
        Long userId = currentUser.getId();
        Map<String, Object> userAnswers = (Map<String, Object>) data.get("answers");

        // 打印 userAnswers 的内容
        System.out.println("User Answers: " + userAnswers);

        // 获取试卷对应的试题列表
        List<ExamQuestion> examQuestions = examQuestionService.listByExaminationId(examId);

        // 计算总分
        double totalScore = 0;
        List<String> nullScoreQuestions = new ArrayList<>(); // 记录分数为 null 的题目

        for (ExamQuestion eq : examQuestions) {
            Question question = questionService.getById(eq.getQuestionId());
            String questionIdStr = String.valueOf(eq.getQuestionId()); // 将 questionId 转换为字符串类型
            Object userAnswer = userAnswers.get(questionIdStr);

            // 添加日志打印
            System.out.println("Question ID: " + questionIdStr);
            System.out.println("User Answer: " + userAnswer);

            // 检查分数是否为 null
            if (question.getScore() == null) {
                nullScoreQuestions.add(questionIdStr);
                continue; // 跳过该题的评分
            }

            double score = scoreCalculator.calculateScore(question, userAnswer);
            totalScore += score;
        }

        // 保存用户答案到exam_detail表
        examDetailService.saveExamDetails(userId, userAnswers, examQuestions);
        // 保存用户答案到内存
        UserAnswersCache.saveUserAnswers(examId, userAnswers);
        Examination examination = examinationService.getById(examId);
        if (examination != null) {
            ExamHistory examHistory = new ExamHistory();
            examHistory.setUserId(userId);
            examHistory.setExamId(examId);
            examHistory.setExamName(examination.getName());
            examHistory.setTotalScore(totalScore);
            examHistory.setExamTime(new Date());

            examHistoryService.saveExamHistory(examHistory);
        }
        // 返回总分和分数为 null 的题目提示
        Map<String, Object> result = new HashMap<>();
        result.put("totalScore", totalScore);
        if (!nullScoreQuestions.isEmpty()) {
            result.put("nullScoreQuestions", nullScoreQuestions);
        }
        return R.ok(result);
    }
    private String getCurrentUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        } else {
            return principal.toString();
        }
    }

    /**
     * 获取考试结果
     * @param examId
     * @return
     */
//    @GetMapping("/result/{examId}")
//    public R getExamResult(@PathVariable Long examId) {
//        // 获取试卷对应的试题列表
//        List<ExamQuestion> examQuestions = examQuestionService.listByExaminationId(examId);
//
//        // 获取用户提交的答案
//        Map<String, Object> userAnswers = UserAnswersCache.getUserAnswers(examId);
//
//        // 计算总分和每题的对错情况
//        double totalScore = 0;
//        List<Map<String, Object>> questionResults = new ArrayList<>();
//
//        for (ExamQuestion eq : examQuestions) {
//            Question question = questionService.getById(eq.getQuestionId());
//            String questionIdStr = String.valueOf(eq.getQuestionId()); // 将 questionId 转换为字符串类型
//
//            // 获取正确答案
//            List<Answer> correctAnswers = answerService.list(new QueryWrapper<Answer>()
//                    .eq("question_id", question.getId())
//                    .eq("is_answer", true));
//
//            // 获取用户答案
//            Object userAnswer = userAnswers.get(questionIdStr);
//
//            // 计算得分
//            double score = scoreCalculator.calculateScore(question, userAnswer);
//            totalScore += score;
//
//            // 判断对错
//            boolean isCorrect = score > 0;
//
//            // 构建每题的结果
//            Map<String, Object> questionResult = new HashMap<>();
//            questionResult.put("title", question.getTitle());
//            questionResult.put("type", question.getType());
//            questionResult.put("score", question.getScore());
//            questionResult.put("userAnswer", userAnswer);
//            questionResult.put("correctAnswer", correctAnswers.stream().map(Answer::getAnswerContent).collect(Collectors.toList()));
//            questionResult.put("isCorrect", isCorrect);
//
//              questionResults.add(questionResult);
//        }
//
//        // 返回结果
//        Map<String, Object> result = new HashMap<>();
//        result.put("totalScore", totalScore);
//        result.put("questions", questionResults);
//        return R.ok(result);
//    }
    /**
     * 获取考试结果
     * @param examId
     * @return
     */
    @GetMapping("/result/{examId}")
    public R getExamResult(@PathVariable Long examId) {
        // 获取试卷对应的试题列表
        List<ExamQuestion> examQuestions = examQuestionService.listByExaminationId(examId);

        // 获取用户提交的答案
        Map<String, Object> userAnswers = UserAnswersCache.getUserAnswers(examId);

        // 计算总分和每题的对错情况
        double totalScore = 0;
        List<Map<String, Object>> questionResults = new ArrayList<>();

        for (ExamQuestion eq : examQuestions) {
            Question question = questionService.getById(eq.getQuestionId());
            String questionIdStr = String.valueOf(eq.getQuestionId()); // 将 questionId 转换为字符串类型

            // 获取正确答案
            List<Answer> correctAnswers = answerService.list(new QueryWrapper<Answer>()
                    .eq("question_id", question.getId())
                    .eq("is_answer", true));

            // 获取用户答案
            Object userAnswer = userAnswers.get(questionIdStr);

            // 计算得分
            double score = scoreCalculator.calculateScore(question, userAnswer);
            totalScore += score;

            // 判断对错
            boolean isCorrect = score > 0;

            // 构建每题的结果
            Map<String, Object> questionResult = new HashMap<>();
            questionResult.put("title", question.getTitle());
            questionResult.put("type", question.getType());
            questionResult.put("score", question.getScore());
            questionResult.put("userAnswer", userAnswer);
            questionResult.put("correctAnswer", correctAnswers.stream().map(Answer::getAnswerContent).collect(Collectors.toList()));
            questionResult.put("correctAnswerId", correctAnswers.stream().map(Answer::getId).collect(Collectors.toList())); // 添加答案ID
            questionResult.put("isCorrect", isCorrect);

            questionResults.add(questionResult);
        }

        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("totalScore", totalScore);
        result.put("questions", questionResults);
        return R.ok(result);
    }
}
